import Vue from 'vue'
import axios from 'axios'
import {
  baseURL,
  contentType,
  debounce,
  invalidCode,
  loginInterception,
  noPermissionCode,
  requestTimeout,
  successCode,
  tokenTableName,
} from '@/config'
import store from '@/store'
import qs from 'qs'
import router from '@/router'
import { isArray } from '@/utils/validate'
import { WebReLogin } from '@/api/MqttLinker'
//显示加载动画或者处理加载状态
let loadingInstance

/**
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
//处理后端接口返回的错误码
const handleCode = (code, msg) => {
  switch (code) {
    case invalidCode: //登录失效code:1001
      Vue.prototype.$baseMessage(msg || `后端接口${code}异常`, 'error')
      store.dispatch('user/resetAccessToken').catch(() => {}) //重置访问令牌
      //loginInterception: 是否开启登录拦截
      if (loginInterception) {
        location.reload() //重新加载当前页面
      }
      break
    case noPermissionCode: //无权限code:401
      router.push({ path: '/401' }).catch(() => {})
      break
    case 404: //无权限code:401
      router.push({ path: '/404' }).catch(() => {})
      break
    case 4001:
      Vue.prototype.$baseMessage(msg || `后端接口${code}异常`, 'error')
      store.dispatch('user/resetAccessToken').catch(() => {}) //重置访问令牌
      //loginInterception: 是否开启登录拦截
      if (loginInterception) {
        location.reload() //重新加载当前页面
      }
      break
    default:
      Vue.prototype.$baseMessage(msg || `后端接口${code}异常`, 'error')
      break
  }
}
//HTTP请求实例
const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    'Content-Type': contentType,
  },
})
//请求拦截器,请求之前对请求进行一些处理
instance.interceptors.request.use(
  (config) => {
    console.log(config, '请求前')
    //检查是否存在用户的访问令牌
    if (store.getters['user/accessToken']) {
      let token = JSON.parse(localStorage.getItem('Token'))
      //config.headers[tokenTableName] = store.getters['user/accessToken']
      config.headers[tokenTableName] = token
    }
    /* //这里会过滤所有为空、0、false的key，如果不需要请自行注释
    if (config.data) config.data = Vue.prototype.$baseLodash.pickBy(config.data, Vue.prototype.$baseLodash.identity) */
    // 判断检查请求头中的Content-Type是否为application/x-www-form-urlencoded;charset=UTF-8，如果是，将请求数据转换为URL编码的形式
    /* if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8')
      config.data = qs.stringify(config.data) */
    //判断检查请求的URL是否包含在debounce数组中的任何一个元素。如果是的话，执行加载动画

    /*    this.$baseColorfullLoading(1) */

    if (debounce.some((item) => config.url.includes(item))) loadingInstance = Vue.prototype.$baseLoading()

    return config
  },
  (error) => {
    console.log(error, '请求发出错误')
    return Promise.reject(error)
  }
)

let isRefreshing = false

let setund = 0

//请求拦截器,处理请求的返回结果和错误信息
instance.interceptors.response.use(
  (response) => {
    //如果有动画，关闭加载动画
    console.log(response, '请求结果')
    if (loadingInstance) loadingInstance.close()

    const { data, config } = response
    const code = response.status
    const msg = response.statusText

    // 操作正常Code数组 [1000,200, 0]
    const codeVerificationArray = isArray(successCode) ? [...successCode] : [...[successCode]]
    // 是否操作正常
    if (codeVerificationArray.includes(code)) {
      let datacode = data.code
      let datamsg = data.msg
      if (codeVerificationArray.includes(datacode)) {
        return data
      } else {
        handleCode(datacode, datamsg)
        return Promise.reject(
          `请求异常拦截:${JSON.stringify({
            url: config.url,
            datacode,
            datamsg,
          })}` || 'Error'
        )
      }
    } else {
      handleCode(code, msg)
      return Promise.reject(
        `请求异常拦截:${JSON.stringify({
          url: config.url,
          code,
          msg,
        })}` || 'Error'
      )
    }
  },
  (error) => {
    console.log(error, '请求结果error')
    if ((error.response.status === 401 || error.response.status === 403) && setund < 3) {
      setund = setund + 1
      let retoken = ''
      if (!isRefreshing) {
        isRefreshing = true
        WebReLogin({
          uName: 'manager',
          uPsw: 'manager@123.com',
        }).then((res) => {
          retoken = res.data
          localStorage.setItem('Token', JSON.stringify(retoken))
          error.config.headers[tokenTableName] = retoken
          error.config.headers['Content-Type'] = contentType
        })
      }
      return instance(error.config)
    } else {
      //关闭动画
      if (loadingInstance) loadingInstance.close()
      const { response, message } = error
      if (error.response && error.response.data) {
        const { status, data } = response
        handleCode(data.code, data.msg || message)
        return Promise.reject(error)
      } else {
        let { message } = error
        if (message === 'Network Error') {
          message = '后端接口连接异常，请重新登录'
        }
        if (message.includes('timeout')) {
          message = '后端接口请求超时'
        }
        if (message.includes('Request failed with status code')) {
          const code = message.substr(message.length - 3)
          message = `后端接口${code}异常`
        }
        Vue.prototype.$baseMessage(message || `后端接口未知异常`, 'error')
        return Promise.reject(error)
      }
    }

    // //关闭动画
    // if (loadingInstance) loadingInstance.close()
    // const { response, message } = error
    // if (error.response && error.response.data) {
    //   const { status, data } = response
    //   handleCode(data.code, data.msg || message)
    //   return Promise.reject(error)
    // } else {
    //   let { message } = error
    //   if (message === 'Network Error') {
    //     message = '后端接口连接异常，请重新登录'
    //   }
    //   if (message.includes('timeout')) {
    //     message = '后端接口请求超时'
    //   }
    //   if (message.includes('Request failed with status code')) {
    //     const code = message.substr(message.length - 3)
    //     message = `后端接口${code}异常`
    //   }
    //   Vue.prototype.$baseMessage(message || `后端接口未知异常`, 'error')
    //   return Promise.reject(error)
    // }
  }
)

export default instance
